
package com.scalar.chiptrack.sales.actions;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMapping;
import org.apache.struts.util.MessageResources;
import org.apache.struts.util.LabelValueBean;

import com.scalar.ScalarException;
import com.scalar.chiptrack.ChipTrackAction;
import com.scalar.chiptrack.operations.vendor.dao.VendorDAO;
import com.scalar.chiptrack.commons.Address;
import com.scalar.chiptrack.commons.Labels;
import com.scalar.chiptrack.commons.SessionKeys;
import com.scalar.chiptrack.commons.Constants;
import com.scalar.chiptrack.db.DBTransaction;
import com.scalar.chiptrack.sales.Customer;
import com.scalar.chiptrack.sales.dao.CustomerDAO;
import com.scalar.chiptrack.sales.dao.EndUserDAO;
import com.scalar.chiptrack.sales.dao.NewCustomerDAO;
import com.scalar.chiptrack.sales.dao.NewSalesOrderDAO;
import com.scalar.chiptrack.sales.dao.SalesDAO;
import com.scalar.chiptrack.sales.forms.CustomerForm;
import com.scalar.chiptrack.users.User;

public final class CustomerAction extends ChipTrackAction
{
    private static final String ACTION_NAME = "/customers.do";

	public ActionForward execute ( ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response ) throws Exception
    {

        String action = request.getParameter ( "action" );

        CustomerForm subform = ( CustomerForm ) form;
        HttpSession session = request.getSession ();
        User user = ( User ) session.getAttribute ( SessionKeys.USER_KEY );

        if ( user == null )
        {
            session.setAttribute ( SessionKeys.SOURCE_PAGE_KEY, ACTION_NAME + "?" + request.getQueryString () );
            return ( mapping.findForward ( "login" ) );
        }

        HashMap info = new LinkedHashMap ();
        request.setAttribute ( SessionKeys.INFO_MESSAGES, info );
        HashMap errors = new LinkedHashMap ();
        request.setAttribute ( SessionKeys.ERROR_MESSAGES, errors );
        if( action == null )
        {
            return ( mapping.findForward("successCustomer") );
        }

        //Load the reason codes in request
        request.setAttribute ( "marketingReasonCodes", SalesDAO.loadMarketingReasonCodes () );
        request.setAttribute ( "salesReasonCodes", SalesDAO.loadSalesReasonCodes () );
        request.setAttribute ( "financeReasonCodes", SalesDAO.loadFinanceReasonCodes () );
        request.setAttribute ( "opsReasonCodes", SalesDAO.loadOpsReasonCodes () );

        if ( ( action == "" ) || ( action.equals ( "" ) ) )
        {
        	int customerId = Integer.parseInt ( request.getParameter ( "customer.customerId" ) );
            request.setAttribute( "customerTypesCollection", CustomerDAO.getAllCustomerTypeList( null ) );
            request.setAttribute ( "regions", CustomerDAO.getAllRegionNames () );
            request.setAttribute ( "shippingInstructions", NewSalesOrderDAO.loadShippingInstructions( null ) );
            request.setAttribute ( "repOffices", CustomerDAO.getAllRepOfficesForCustomer ( Integer.parseInt ( request.getParameter ( "customer.customerId" ) ) ) );
            request.setAttribute ( "salesPersonsList", CustomerDAO.loadAllSalesPersonsforCustomer( Integer.parseInt ( request.getParameter ( "customer.customerId" ) ) ) );
            request.setAttribute ( "salesRepList", CustomerDAO.getAllSalesRepsForCustomer ( Integer.parseInt ( request.getParameter ( "customer.customerId" ) ) ) );
            request.setAttribute ( "customerContactPersonsList", CustomerDAO.getAllContactPersonsForCustomer ( Integer.parseInt ( request.getParameter ( "customer.customerId" ) ) ) );
            request.setAttribute ( "customerContactPersonsMap", CustomerDAO.getContactPersonDetailsMap ( Integer.parseInt ( request.getParameter ( "customer.customerId" ) ) ) );


            ArrayList shippingLocs = subform.getCustomer().getShippingLocations();
			HashMap allShippingContactPersons = new HashMap();

            updateAddressesAndContactPersonsMap(shippingLocs, allShippingContactPersons);

            ArrayList billingLocs = subform.getCustomer().getBillingLocations();
			HashMap allBillingContactPersons = new HashMap();

            updateAddressesAndContactPersonsMap(billingLocs, allBillingContactPersons);

            if( customerId < 0 )
			{
				request.setAttribute ( "billingContactPersonsList", CustomerDAO.getAllContactPersonsForAddress( subform.getCustomer().getBillAddressId()) );
				request.setAttribute ( "billingContactPersonsMap", CustomerDAO.getAddressContactPersonDetailsMap ( subform.getCustomer().getBillAddressId() ) );
				request.setAttribute ( "shippingContactPersonsList", CustomerDAO.getAllContactPersonsForAddress( subform.getCustomer().getShipAddressId() ) );
				request.setAttribute ( "shippingContactPersonsMap", CustomerDAO.getAddressContactPersonDetailsMap ( subform.getCustomer().getShipAddressId() ) );
                request.setAttribute ( "salesPersonsRegionList" , NewCustomerDAO.loadAllSalesPersonsWithRegions() );
				request.setAttribute ( "allShippingContactPersonsMap", allShippingContactPersons );
				request.setAttribute ( "allBillingContactPersonsMap", allBillingContactPersons );
			}
			else
			{
				request.setAttribute ( "billingContactPersonsList", CustomerDAO.getAllContactPersonsForAddress( Integer.parseInt ( request.getParameter ( "customer.defaultBillingAddressId" ) ) ) );
				request.setAttribute ( "billingContactPersonsMap", CustomerDAO.getAddressContactPersonDetailsMap ( Integer.parseInt ( request.getParameter ( "customer.defaultBillingAddressId" ) ) ) );
				request.setAttribute ( "shippingContactPersonsList", CustomerDAO.getAllContactPersonsForAddress( Integer.parseInt ( request.getParameter ( "customer.defaultShippingAddressId" ) ) ) );
				request.setAttribute ( "shippingContactPersonsMap", CustomerDAO.getAddressContactPersonDetailsMap ( Integer.parseInt ( request.getParameter ( "customer.defaultShippingAddressId" ) ) ) );
                request.setAttribute ( "salesPersonsRegionList" , NewCustomerDAO.loadAllSalesPersonsWithRegions() );
				request.setAttribute ( "allShippingContactPersonsMap", allShippingContactPersons );
                request.setAttribute ( "allBillingContactPersonsMap", allBillingContactPersons );
            }

			request.setAttribute ( "showCustomer", session.getAttribute ( "showCustomer" ) );
            request.setAttribute ( "shippingMethods", CustomerDAO.loadAllShippingMethods ( Integer.parseInt ( request.getParameter ( "customer.customerId" ) ) ) );
            request.setAttribute ( "deliveryTerms", CustomerDAO.getAllDeliveryTerms(null) );
            request.setAttribute ( "allShippingTerms", SalesDAO.getAllShippingTerms() );

            ArrayList endUsers = EndUserDAO.getAllEndUserNames ( Integer.parseInt ( request.getParameter ( "customer.customerId" ) ) );
            request.setAttribute ( "endUsers", endUsers );

            return ( mapping.findForward ( "editCustomer" ) );
        }

        if ( "CreateCustomer".equals ( action ) )
        {
            Customer customer = new Customer ();
            request.setAttribute( "customerTypesCollection", CustomerDAO.getAllCustomerTypeList( null ) );

            ArrayList shippingList = new ArrayList ();
            Address shippingAddress = new Address ();
            shippingList.add ( shippingAddress );
            customer.setShippingLocations ( shippingList );
            customer.setBillingLocations(new ArrayList());
            customer.setEndUserName ( "" );

            ArrayList shipmethods = CustomerDAO.loadAllShippingMethods ( -1 );

            subform.setCustomer ( customer );
            subform.setAction ( action );

            session.setAttribute ( "locations", CustomerDAO.loadAllVendorLocationsForCustomer () );
            session.setAttribute ( "showCustomer", "TRUE" );
            request.setAttribute ( "regions", CustomerDAO.getAllRegionNames () );
            request.setAttribute ( "shippingInstructions", NewSalesOrderDAO.loadShippingInstructions( null ) );
            request.setAttribute ( "repOffices", CustomerDAO.getAllRepOfficesForCustomer ( customer.getCustomerId () ) );
            request.setAttribute ( "salesPersonsList", CustomerDAO.loadAllSalesPersonsforCustomer( customer.getCustomerId () ) );
            request.setAttribute ( "salesRepList", CustomerDAO.getAllSalesRepsForCustomer ( customer.getCustomerId () ) );
            request.setAttribute ( "customerContactPersonsList", CustomerDAO.getAllContactPersonsForCustomer ( customer.getCustomerId () ) );
            request.setAttribute ( "customerContactPersonsMap", CustomerDAO.getContactPersonDetailsMap ( customer.getCustomerId () ) );
			request.setAttribute ( "billingContactPersonsList", CustomerDAO.getAllContactPersonsForAddress( customer.getBillAddressId() ) );
			request.setAttribute ( "billingContactPersonsMap", CustomerDAO.getAddressContactPersonDetailsMap ( customer.getBillAddressId() ) );
			request.setAttribute ( "shippingContactPersonsList", CustomerDAO.getAllContactPersonsForAddress( customer.getShipAddressId() ) );
			request.setAttribute ( "shippingContactPersonsMap", CustomerDAO.getAddressContactPersonDetailsMap ( customer.getShipAddressId() ) );
            request.setAttribute ( "salesPersonsRegionList" , NewCustomerDAO.loadAllSalesPersonsWithRegions() );
			request.setAttribute ( "allShippingContactPersonsMap", CustomerDAO.getAllContactPersonsOfType( customer.getCustomerId(), "Shipping") );
			request.setAttribute ( "allBillingContactPersonsMap", CustomerDAO.getAllContactPersonsOfType( customer.getCustomerId(), "Billing") );

            request.setAttribute ( "endUsers", new ArrayList () );

            request.setAttribute ( "shippingMethods", shipmethods );
            request.setAttribute ( "deliveryTerms", CustomerDAO.getAllDeliveryTerms(null) );
            request.setAttribute ( "allShippingTerms", SalesDAO.getAllShippingTerms());

            customer.setOperationsHold( "0" );
            customer.setSalesHold( "0" );
            customer.setFinanceHold( "0" );
            customer.setMarketingHold ( "0" );

            customer.setSampleOperationsHold( "0" );
            customer.setSampleSalesHold( "0" );
            customer.setSampleFinanceHold( "0" );
            customer.setSampleMarketingHold ( "0" );

            saveToken ( request );
            return ( mapping.findForward ( "editCustomer" ) );
        }
        else if ( "EditCustomer".equals ( action ) )
        {
            Customer customer = CustomerDAO.getCustomerDetails ( Integer.parseInt ( request.getParameter ( "customerId" ) ) );
            request.setAttribute( "customerTypesCollection", CustomerDAO.getAllCustomerTypeList( null ) );

            String selectedMethod1 = customer.getShippingMethod1 ();
            String selectedAccount1 = customer.getShippingAccount1 ();

            if ( selectedMethod1 != null )
                selectedMethod1 = selectedMethod1.trim ();
            if ( selectedAccount1 != null )
                selectedAccount1 = selectedAccount1.trim ();

            request.setAttribute ( "Method1", selectedMethod1 + "   #   " + selectedAccount1 );
            request.setAttribute ( "Account1", selectedMethod1 + "   #   " + selectedAccount1 );

            subform.setCustomer ( customer );
            subform.setAction ( action );

            session.setAttribute ( "locations", CustomerDAO.loadAllVendorLocationsForCustomer () );
            request.setAttribute ( "regions", CustomerDAO.getAllRegionNames() );
            request.setAttribute ( "shippingInstructions", NewSalesOrderDAO.loadShippingInstructions( null ) );
            request.setAttribute ( "repOffices", CustomerDAO.getAllRepOfficesForCustomer ( Integer.parseInt ( request.getParameter ( "customerId" ) ) ) );
            request.setAttribute ( "salesPersonsList", CustomerDAO.loadAllSalesPersonsforCustomer( Integer.parseInt ( request.getParameter ( "customerId" ) ) ) );
            request.setAttribute ( "salesRepList", CustomerDAO.getAllSalesRepsForCustomer ( Integer.parseInt ( request.getParameter ( "customerId" ) ) ) );
            request.setAttribute ( "customerContactPersonsList", CustomerDAO.getAllContactPersonsForCustomer ( Integer.parseInt ( request.getParameter ( "customerId" ) ) ) );
            request.setAttribute ( "customerContactPersonsMap", CustomerDAO.getContactPersonDetailsMap ( Integer.parseInt ( request.getParameter ( "customerId" ) ) ) );
			request.setAttribute ( "billingContactPersonsList", CustomerDAO.getAllContactPersonsForAddress( customer.getDefaultBillingAddressId() ) );
			request.setAttribute ( "billingContactPersonsMap", CustomerDAO.getAddressContactPersonDetailsMap ( customer.getDefaultBillingAddressId()) );
			request.setAttribute ( "shippingContactPersonsList", CustomerDAO.getAllContactPersonsForAddress( customer.getDefaultShippingAddressId() ) );
			request.setAttribute ( "shippingContactPersonsMap", CustomerDAO.getAddressContactPersonDetailsMap ( customer.getDefaultShippingAddressId() ) );
            request.setAttribute ( "salesPersonsRegionList" , NewCustomerDAO.loadAllSalesPersonsWithRegions() );
			request.setAttribute ( "allShippingContactPersonsMap", CustomerDAO.getAllContactPersonsOfType( customer.getCustomerId(), "Shipping") );
			request.setAttribute ( "allBillingContactPersonsMap", CustomerDAO.getAllContactPersonsOfType( customer.getCustomerId(), "Billing") );
            request.setAttribute ( "deliveryTerms", CustomerDAO.getAllDeliveryTerms(null) );
            request.setAttribute ( "allShippingTerms", SalesDAO.getAllShippingTerms());
            ArrayList shipMethods = CustomerDAO.loadAllShippingMethods ( Integer.parseInt ( request.getParameter ( "customerId" ) ) );
            request.setAttribute ( "shippingMethods", shipMethods );

            session.setAttribute ( "showCustomer", "FALSE" );

            customer.setEndUserName ( "" );
            request.setAttribute ( "endUsers", EndUserDAO.getAllEndUserNames ( Integer.parseInt ( request.getParameter ( "customerId" ) ) ) );

            saveToken ( request );
            return ( mapping.findForward ( "editCustomer" ) );
        }
        else if ( ( "ViewCustomer".equals ( action ) ) || ( "PrintCustomer".equals ( action ) ) )
        {
            String flag = request.getParameter ( "flag" );
            Customer customer = CustomerDAO.getCustomerDetails ( Integer.parseInt ( request.getParameter ( "customerId" ) ) );
            customer.setCustomerTypeList( CustomerDAO.getCustomerTypeList( null, customer.getCustomerId() ) );

            customer.setSelectedLocations ( CustomerDAO.selectedLocationsForCustomer ( customer.getSelectedLocations () ) );
            if ( ( customer.getShippingMethod1 () == null || customer.getShippingMethod1 ().length () == 0 ) && ( customer.getShippingAccount1 () == null || customer.getShippingAccount1 ().length () == 0 ) )
            {
                customer.setShippingMethod1 ( "" );
            }
            else
            {
                customer.setShippingMethod1 ( customer.getShippingMethod1 () + "   #   " + customer.getShippingAccount1 () );
            }
            subform.setCustomer ( customer );
            if ( action.equals ( "PrintCustomer" ) )
            {
                return ( mapping.findForward ( "printCustomer" ) );
            }
            else
            {
                if ( "True".equalsIgnoreCase ( flag ) )
                {
                    request.setAttribute ( "setConfirm", "Yes" );
                    return ( mapping.findForward ( "viewCustomer" ) );
                }
                else
                {
                    return ( mapping.findForward ( "viewCustomer" ) );
                }

            }//else
        }
        else if ( "DeleteAfterConfirm".equals ( action ) )
        {

            boolean checkSalesOrder = CustomerDAO.doesSalesOrderExist ( null, Integer.parseInt ( request.getParameter ( "customerId" ) ) );
            boolean checkQuotetion = CustomerDAO.doescheckQuotetionExist ( null, Integer.parseInt ( request.getParameter ( "customerId" ) ) );
            ArrayList regionsList = CustomerDAO.getAllRegionNames();
            ArrayList repOfficesList = CustomerDAO.getAllRepOfficesForCustomer();
            ArrayList customersList = CustomerDAO.getAllCustomers();

            request.setAttribute ( "regions", regionsList );
            request.setAttribute ( "repOffices", repOfficesList );
            request.setAttribute ( "customerslist", customersList );
            request.setAttribute ( "shippingInstructions", NewSalesOrderDAO.loadShippingInstructions( null ) );

            if ( ( checkSalesOrder == false )&&( checkQuotetion == false) )
            {
                CustomerDAO.deleteCustomer ( Integer.parseInt ( request.getParameter ( "customerId" ) ) );
                request.setAttribute ( "Confirm", "DELETE" );
                request.setAttribute ( "Confirmquote", "EscapeNull" );
            }
            else if( ( checkSalesOrder == true )&&( checkQuotetion == false ) )
            {
                request.setAttribute ( "Confirm", "DONTDELETE" );
                request.setAttribute ( "Confirmquote", "EscapeNull" );
            }
            else if( ( checkSalesOrder == false )&&( checkQuotetion == true ) )
            {
                request.setAttribute ( "Confirmquote", "DONTDELETEQUOTE" );
                request.setAttribute ( "Confirm", "EscapeNull" );
            }
            else
            {
                request.setAttribute ( "Confirm", "DONTDELETE" );
                request.setAttribute ( "Confirmquote", "DONTDELETEQUOTE" );
            }
            return ( mapping.findForward ( "deletesuccessfully" ) );
        }

        else if ( "CancelPage".equals ( action ) )
        {
            return ( mapping.findForward ( "deletesuccessfully" ) );

        }
        else if ( "CustomerContinue".equals ( action ) )
        {
            Customer customer = subform.getCustomer ();
            subform.setCustomer ( customer );
            request.setAttribute ( "customerForm", subform );

            return ( mapping.findForward ( "nextPage" ) );
        }
        else if ( "loadShippingInstructions".equals ( action ) )
        {
        	int customerId = Integer.parseInt ( request.getParameter ( "customer.customerId" ) );

            subform.getCustomer().setShippingInstructions ( NewSalesOrderDAO.loadSelectedShippingInstructions( null, Integer.parseInt( request.getParameter ( "customer.shippingInstructionsId" ) ) ) );

            request.setAttribute( "customerTypesCollection", CustomerDAO.getAllCustomerTypeList( null ) );
            request.setAttribute ( "regions", CustomerDAO.getAllRegionNames () );
            request.setAttribute ( "shippingInstructions", NewSalesOrderDAO.loadShippingInstructions( null ) );
            request.setAttribute ( "repOffices", CustomerDAO.getAllRepOfficesForCustomer ( Integer.parseInt ( request.getParameter ( "customer.customerId" ) ) ) );
            request.setAttribute ( "salesPersonsList", CustomerDAO.loadAllSalesPersonsforCustomer( Integer.parseInt ( request.getParameter ( "customer.customerId" ) ) ) );
            request.setAttribute ( "salesRepList", CustomerDAO.getAllSalesRepsForCustomer ( Integer.parseInt ( request.getParameter ( "customer.customerId" ) ) ) );
            request.setAttribute ( "customerContactPersonsList", CustomerDAO.getAllContactPersonsForCustomer ( Integer.parseInt ( request.getParameter ( "customer.customerId" ) ) ) );
            request.setAttribute ( "customerContactPersonsMap", CustomerDAO.getContactPersonDetailsMap ( Integer.parseInt ( request.getParameter ( "customer.customerId" ) ) ) );

			ArrayList shippingLocs = subform.getCustomer().getShippingLocations();
			HashMap allShippingContactPersonsMap = new HashMap();
			updateAddressesAndContactPersonsMap(shippingLocs, allShippingContactPersonsMap);

            ArrayList BillingLocs = subform.getCustomer().getBillingLocations();
            HashMap allBillingContactPersonsMap = new HashMap();
            updateAddressesAndContactPersonsMap(BillingLocs, allBillingContactPersonsMap);
            if( customerId < 0 )
			{
				request.setAttribute ( "billingContactPersonsList", CustomerDAO.getAllContactPersonsForAddress( subform.getCustomer().getBillAddressId()) );
				request.setAttribute ( "billingContactPersonsMap", CustomerDAO.getAddressContactPersonDetailsMap ( subform.getCustomer().getBillAddressId() ) );
				request.setAttribute ( "shippingContactPersonsList", CustomerDAO.getAllContactPersonsForAddress( subform.getCustomer().getShipAddressId() ) );
				request.setAttribute ( "shippingContactPersonsMap", CustomerDAO.getAddressContactPersonDetailsMap ( subform.getCustomer().getShipAddressId() ) );
                request.setAttribute ( "salesPersonsRegionList" , NewCustomerDAO.loadAllSalesPersonsWithRegions() );
				request.setAttribute ( "allShippingContactPersonsMap", allShippingContactPersonsMap );
				request.setAttribute ( "allBillingContactPersonsMap", allBillingContactPersonsMap );
			}
			else
			{
				request.setAttribute ( "billingContactPersonsList", CustomerDAO.getAllContactPersonsForAddress( Integer.parseInt ( request.getParameter ( "customer.defaultBillingAddressId" ) ) ) );
				request.setAttribute ( "billingContactPersonsMap", CustomerDAO.getAddressContactPersonDetailsMap ( Integer.parseInt ( request.getParameter ( "customer.defaultBillingAddressId" ) ) ) );
				request.setAttribute ( "shippingContactPersonsList", CustomerDAO.getAllContactPersonsForAddress( Integer.parseInt ( request.getParameter ( "customer.defaultShippingAddressId" ) ) ) );
				request.setAttribute ( "shippingContactPersonsMap", CustomerDAO.getAddressContactPersonDetailsMap ( Integer.parseInt ( request.getParameter ( "customer.defaultShippingAddressId" ) ) ) );
                request.setAttribute ( "salesPersonsRegionList" , NewCustomerDAO.loadAllSalesPersonsWithRegions() );
				request.setAttribute ( "allBillingContactPersonsMap", allBillingContactPersonsMap );
			}

			request.setAttribute ( "showCustomer", session.getAttribute ( "showCustomer" ) );
            request.setAttribute ( "shippingMethods", CustomerDAO.loadAllShippingMethods ( Integer.parseInt ( request.getParameter ( "customer.customerId" ) ) ) );
            request.setAttribute ( "deliveryTerms", CustomerDAO.getAllDeliveryTerms(null) );
            request.setAttribute ( "allShippingTerms", SalesDAO.getAllShippingTerms());
            ArrayList endUsers = EndUserDAO.getAllEndUserNames ( Integer.parseInt ( request.getParameter ( "customer.customerId" ) ) );
            request.setAttribute ( "endUsers", endUsers );

            return ( mapping.findForward ( "editCustomer" ) );
        }
        else if ( "SaveCustomer".equals ( action ) )
        {
            Customer customer = subform.getCustomer ();
            customer.setCustomerName ( customer.getCustomerName ().trim () );

            String method = "";
            String account = "";
            String temp = customer.getShippingMethod1 ();
            if ( temp != null )
            {
                int index1 = temp.indexOf ( "#" );

                if ( index1 != -1 && index1 != 0 )
                {
                    method = temp.substring ( 0, index1 ).trim ();
                    account = temp.substring ( index1 + 1, temp.length () ).trim ();
                }
            }
            customer.setShippingAccount1 ( account );

            int customerId = -1;
            boolean success = false;
            boolean flag = false;
            DBTransaction dbTransaction = null;

            if ( !isTokenValid ( request ) )
            {
                errors.put ( "This Customers details are already saved, to change it visit Customer details screen ", "" );
            }

            if ( !errors.isEmpty () )
            {
                request.setAttribute ( SessionKeys.ERROR_MESSAGES, errors );
                saveToken ( request );
                return ( mapping.findForward ( "success" ) );
            }

            if ( subform.getCustomer ().getCustomerId ()  < 0 )
            {

                if ( CustomerDAO.isCustomerExists ( subform.getCustomer ().getCustomerName ().trim () ) )
                {
                    ArrayList shipmethods = new ArrayList ();
                    errors.put ( "Customer", "Customer Name already exists, Please enter new name" );
                    request.setAttribute ( SessionKeys.ERROR_MESSAGES, errors );
                    subform.setAction ( "CreateCustomer" );
                    saveToken ( request );

                    request.setAttribute( "customerTypesCollection", CustomerDAO.getAllCustomerTypeList( null ) );
                    request.setAttribute ( "regions", CustomerDAO.getAllRegionNames() );
                    request.setAttribute ( "shippingInstructions", NewSalesOrderDAO.loadShippingInstructions( null ) );
                    request.setAttribute ( "repOffices", CustomerDAO.getAllRepOfficesForCustomer ( subform.getCustomer ().getCustomerId() ) );
                    request.setAttribute ( "salesPersonsList", CustomerDAO.loadAllSalesPersonsforCustomer( subform.getCustomer ().getCustomerId() ) );
                    request.setAttribute ( "salesRepList", CustomerDAO.getAllSalesRepsForCustomer ( subform.getCustomer ().getCustomerId() ) );
                    request.setAttribute ( "customerContactPersonsList", CustomerDAO.getAllContactPersonsForCustomer ( subform.getCustomer ().getCustomerId() ) );
					request.setAttribute ( "customerContactPersonsMap", CustomerDAO.getContactPersonDetailsMap ( subform.getCustomer ().getCustomerId() ) );
					request.setAttribute ( "billingContactPersonsList", CustomerDAO.getAllContactPersonsForAddress( subform.getCustomer ().getBillAddressId()) );
					request.setAttribute ( "billingContactPersonsMap", CustomerDAO.getAddressContactPersonDetailsMap ( subform.getCustomer ().getBillAddressId() ) );
					request.setAttribute ( "shippingContactPersonsList", CustomerDAO.getAllContactPersonsForAddress( subform.getCustomer ().getShipAddressId() ) );
					request.setAttribute ( "shippingContactPersonsMap", CustomerDAO.getAddressContactPersonDetailsMap ( subform.getCustomer ().getShipAddressId() ) );
                    request.setAttribute ( "salesPersonsRegionList" , NewCustomerDAO.loadAllSalesPersonsWithRegions() );
                    request.setAttribute ( "deliveryTerms", CustomerDAO.getAllDeliveryTerms(null) );
                    request.setAttribute ( "allShippingTerms", SalesDAO.getAllShippingTerms());

                    ArrayList shippingLocs = subform.getCustomer().getShippingLocations();
                    HashMap allShippingContactPersonsMap = new HashMap();
                    updateAddressesAndContactPersonsMap(shippingLocs, allShippingContactPersonsMap);

                    ArrayList BillingLocs = subform.getCustomer().getBillingLocations();
                    HashMap allBillingContactPersonsMap = new HashMap();
                    updateAddressesAndContactPersonsMap(BillingLocs, allBillingContactPersonsMap);

					request.setAttribute ( "allShippingContactPersonsMap", allShippingContactPersonsMap );
					request.setAttribute ( "allBillingContactPersonsMap", allBillingContactPersonsMap );


                    request.setAttribute ( "shippingMethods", shipmethods );
                    request.setAttribute ( "endUsers", new ArrayList () );
                    return ( mapping.findForward ( "editCustomer" ) );
                }
                else if ( CustomerDAO.isCustomerNumberExists ( null, subform.getCustomer().getCustomerNumber().trim() ) )
                {
                    ArrayList shipmethods = new ArrayList ();
                    errors.put ( "Customer", "Customer Number already exists, Please enter new number" );
                    request.setAttribute ( SessionKeys.ERROR_MESSAGES, errors );
                    subform.setAction ( "CreateCustomer" );
                    saveToken ( request );

                    request.setAttribute( "customerTypesCollection", CustomerDAO.getAllCustomerTypeList( null ) );
                    request.setAttribute ( "regions", CustomerDAO.getAllRegionNames() );
                    request.setAttribute ( "shippingInstructions", NewSalesOrderDAO.loadShippingInstructions( null ) );
                    request.setAttribute ( "repOffices", CustomerDAO.getAllRepOfficesForCustomer () );
                    request.setAttribute ( "salesPersonsList", CustomerDAO.loadAllSalesPersonsforCustomer( subform.getCustomer ().getCustomerId() ) );
                    request.setAttribute ( "salesRepList", CustomerDAO.getAllSalesRepsForCustomer () );
					request.setAttribute ( "customerContactPersonsList", CustomerDAO.getAllContactPersonsForCustomer ( subform.getCustomer ().getCustomerId() ) );
					request.setAttribute ( "customerContactPersonsMap", CustomerDAO.getContactPersonDetailsMap ( subform.getCustomer ().getCustomerId() ) );
					request.setAttribute ( "billingContactPersonsList", CustomerDAO.getAllContactPersonsForAddress( subform.getCustomer ().getBillAddressId()) );
					request.setAttribute ( "billingContactPersonsMap", CustomerDAO.getAddressContactPersonDetailsMap ( subform.getCustomer ().getBillAddressId() ) );
					request.setAttribute ( "shippingContactPersonsList", CustomerDAO.getAllContactPersonsForAddress( subform.getCustomer ().getShipAddressId() ) );
					request.setAttribute ( "shippingContactPersonsMap", CustomerDAO.getAddressContactPersonDetailsMap ( subform.getCustomer ().getShipAddressId() ) );
                    request.setAttribute ( "salesPersonsRegionList" , NewCustomerDAO.loadAllSalesPersonsWithRegions() );
                    request.setAttribute ( "deliveryTerms", CustomerDAO.getAllDeliveryTerms(null) );
                    request.setAttribute ( "allShippingTerms", SalesDAO.getAllShippingTerms());

                    ArrayList shippingLocs = subform.getCustomer().getShippingLocations();
                    HashMap allShippingContactPersonsMap = new HashMap();
                    updateAddressesAndContactPersonsMap(shippingLocs, allShippingContactPersonsMap);

                    ArrayList BillingLocs = subform.getCustomer().getBillingLocations();
                    HashMap allBillingContactPersonsMap = new HashMap();
                    updateAddressesAndContactPersonsMap(BillingLocs, allBillingContactPersonsMap);

					request.setAttribute ( "allShippingContactPersonsMap", allShippingContactPersonsMap );
					request.setAttribute ( "allBillingContactPersonsMap", allBillingContactPersonsMap );


                    request.setAttribute ( "shippingMethods", shipmethods );
                    request.setAttribute ( "endUsers", new ArrayList () );
                    return ( mapping.findForward ( "editCustomer" ) );
                }
            }

            boolean isNewCustomer = false;
            try
            {
                //Begine Transaction
                dbTransaction = DBTransaction.getInstance ();
                dbTransaction.begin ();
                int rdmCustomerId = subform.getCustomer ().getCustomerId ();
                if ( subform.getCustomer ().getCustomerId ()  < 0 )
                {
                    isNewCustomer = true;
                    addNewShippingInstructions( dbTransaction, request, errors, info, customer );
                    addNewShippingTerms ( dbTransaction, request, session, errors, info, customer );
                    customerId = CustomerDAO.saveCustomerDetails ( dbTransaction, customer );
                    int error_code = CustomerDAO.insertCustomerTypes( dbTransaction, customer.getSelectedCustomerTypes(), customerId );
                    CustomerDAO.saveShipAlertEmails ( dbTransaction, subform.getCustomer () );
                    CustomerDAO.updateRepOffice ( dbTransaction, customerId, rdmCustomerId );
                    CustomerDAO.updateSalesPerson ( dbTransaction, customerId, rdmCustomerId );
                    CustomerDAO.updateSalesRep ( dbTransaction, customerId, rdmCustomerId );
					CustomerDAO.updateCustomerContactPerson ( dbTransaction, customerId, rdmCustomerId );
					CustomerDAO.updateAddressContactPerson ( dbTransaction, customer.getDefaultBillingAddressId(),customer.getBillAddressId() );
					CustomerDAO.updateAddressContactPerson ( dbTransaction, customer.getDefaultShippingAddressId(),customer.getShipAddressId() );
                    EndUserDAO.updateEndUserCustomerIds ( dbTransaction, customerId, rdmCustomerId );
                    subform.getCustomer ().setCustomerId ( customerId );
                    addNewShippingMethod ( dbTransaction, request, session, errors, info, subform );
                    CustomerDAO.saveCustomerHolds ( dbTransaction, customer, user.getUserName(), false );
                    CustomerDAO.saveCustomerHolds ( dbTransaction, customer, user.getUserName(), true );
                }
                else
                {   
                    if(CustomerDAO.isCustomerExists(subform.getCustomer ().getCustomerName ().trim () ,subform.getCustomer ().getCustomerId() ))
                    {
                          errors.put("Customers","Customer Already Exists with the Name "+subform.getCustomer ().getCustomerName ().trim ());
                          request.setAttribute ( SessionKeys.ERROR_MESSAGES, errors );
                          subform.setAction ( "EditCustomer" );
                          int custId = subform.getCustomer ().getCustomerId();
                          customer = CustomerDAO.getCustomerDetails ( subform.getCustomer ().getCustomerId() );
                          request.setAttribute( "customerTypesCollection", CustomerDAO.getAllCustomerTypeList( null ) );

                          String selectedMethod1 = customer.getShippingMethod1 ();
                          String selectedAccount1 = customer.getShippingAccount1 ();
                          if ( selectedMethod1 != null )
                                selectedMethod1 = selectedMethod1.trim ();
                          if ( selectedAccount1 != null )
                                selectedAccount1 = selectedAccount1.trim ();

                          request.setAttribute ( "Method1", selectedMethod1 + "   #   " + selectedAccount1 );
                          request.setAttribute ( "Account1", selectedMethod1 + "   #   " + selectedAccount1 );

                          subform.setCustomer ( customer );
                          subform.setAction ( action );

                          session.setAttribute ( "locations", CustomerDAO.loadAllVendorLocationsForCustomer () );
                          request.setAttribute ( "regions", CustomerDAO.getAllRegionNames() );
                          request.setAttribute ( "shippingInstructions", NewSalesOrderDAO.loadShippingInstructions( null ) );
                          request.setAttribute ( "repOffices", CustomerDAO.getAllRepOfficesForCustomer ( custId ) );
                          request.setAttribute ( "salesPersonsList", CustomerDAO.loadAllSalesPersonsforCustomer( custId ) );
                          request.setAttribute ( "salesRepList", CustomerDAO.getAllSalesRepsForCustomer ( custId ) );
                          request.setAttribute ( "customerContactPersonsList", CustomerDAO.getAllContactPersonsForCustomer ( custId ) );
                          request.setAttribute ( "customerContactPersonsMap", CustomerDAO.getContactPersonDetailsMap ( custId ) );
                          request.setAttribute ( "billingContactPersonsList", CustomerDAO.getAllContactPersonsForAddress( customer.getDefaultBillingAddressId() ) );
                          request.setAttribute ( "billingContactPersonsMap", CustomerDAO.getAddressContactPersonDetailsMap ( customer.getDefaultBillingAddressId()) );
                          request.setAttribute ( "shippingContactPersonsList", CustomerDAO.getAllContactPersonsForAddress( customer.getDefaultShippingAddressId() ) );
                          request.setAttribute ( "shippingContactPersonsMap", CustomerDAO.getAddressContactPersonDetailsMap ( customer.getDefaultShippingAddressId() ) );
                          request.setAttribute ( "salesPersonsRegionList" , NewCustomerDAO.loadAllSalesPersonsWithRegions() );
                          request.setAttribute ( "allShippingContactPersonsMap", CustomerDAO.getAllContactPersonsOfType( customer.getCustomerId(), "Shipping") );
                          request.setAttribute ( "allBillingContactPersonsMap", CustomerDAO.getAllContactPersonsOfType( customer.getCustomerId(), "Billing") );

                          ArrayList shipMethods = CustomerDAO.loadAllShippingMethods ( custId );
                          request.setAttribute ( "shippingMethods", shipMethods );
                          request.setAttribute ( "deliveryTerms", CustomerDAO.getAllDeliveryTerms(null) );
                          session.setAttribute ( "showCustomer", "FALSE" );
                          customer.setEndUserName ( "" );
                          request.setAttribute ( "endUsers", EndUserDAO.getAllEndUserNames ( custId ) );
                          request.setAttribute ( "allShippingTerms", SalesDAO.getAllShippingTerms());
                          flag = true;
                          return (mapping.findForward ("editCustomer"));
                    }
                    else
                    {
                    addNewShippingInstructions( dbTransaction, request, errors, info, customer );
                    addNewShippingTerms (dbTransaction, request, session, errors, info, customer );
                    customerId = CustomerDAO.saveCustomerDetails ( dbTransaction, customer );
                    //addNewShippingMethod ( dbTransaction, request, session, errors, info, subform ); //handled in popup screen
                    int error_code = CustomerDAO.insertCustomerTypes( dbTransaction, customer.getSelectedCustomerTypes(), customerId );
                    String odmName = MessageResources.getMessageResources ( Labels.APPLICATION_RESOURCE_PROPERTIES ).getMessage ( "label.sales.endCustomer" );
                    String endCustomer = MessageResources.getMessageResources ( Labels.APPLICATION_RESOURCE_PROPERTIES ).getMessage ( "label.sales.endUser" );
                    if ( error_code > 0 ) {
                          if ( error_code == 1 ) {
                                errors.put("Error ", "Could not remove the customer type "+ odmName +" as it has relationship with other customers");
                          } else if ( error_code == 2 ) {
                                errors.put("Error ", "Could not remove the customer type "+ endCustomer +" as it has a relationship with other customers");
                          }
                          customer.setSelectedCustomerTypes(  CustomerDAO.loadCustomerTypeRelationShips( null, customerId ));
                          request.setAttribute ( SessionKeys.ERROR_MESSAGES, errors );
                          subform.setAction ( "EditCustomer" );
                          int custId = subform.getCustomer ().getCustomerId();
                          request.setAttribute( "customerTypesCollection", CustomerDAO.getAllCustomerTypeList( null ) );

                          String selectedMethod1 = customer.getShippingMethod1 ();
                          String selectedAccount1 = customer.getShippingAccount1 ();
                          if ( selectedMethod1 != null )
                                selectedMethod1 = selectedMethod1.trim ();
                          if ( selectedAccount1 != null )
                                selectedAccount1 = selectedAccount1.trim ();

                          request.setAttribute ( "Method1", selectedMethod1 + "   #   " + selectedAccount1 );
                          request.setAttribute ( "Account1", selectedMethod1 + "   #   " + selectedAccount1 );

                          subform.setAction ( action );

                          session.setAttribute ( "locations", CustomerDAO.loadAllVendorLocationsForCustomer () );
                          request.setAttribute ( "regions", CustomerDAO.getAllRegionNames() );
                          request.setAttribute ( "shippingInstructions", NewSalesOrderDAO.loadShippingInstructions( null ) );
                          request.setAttribute ( "repOffices", CustomerDAO.getAllRepOfficesForCustomer ( custId ) );
                          request.setAttribute ( "salesPersonsList", CustomerDAO.loadAllSalesPersonsforCustomer( custId ) );
                          request.setAttribute ( "salesRepList", CustomerDAO.getAllSalesRepsForCustomer ( custId ) );
                          request.setAttribute ( "customerContactPersonsList", CustomerDAO.getAllContactPersonsForCustomer ( custId ) );
                          request.setAttribute ( "customerContactPersonsMap", CustomerDAO.getContactPersonDetailsMap ( custId ) );
                          request.setAttribute ( "billingContactPersonsList", CustomerDAO.getAllContactPersonsForAddress( customer.getDefaultBillingAddressId() ) );
                          request.setAttribute ( "billingContactPersonsMap", CustomerDAO.getAddressContactPersonDetailsMap ( customer.getDefaultBillingAddressId()) );
                          request.setAttribute ( "shippingContactPersonsList", CustomerDAO.getAllContactPersonsForAddress( customer.getDefaultShippingAddressId() ) );
                          request.setAttribute ( "shippingContactPersonsMap", CustomerDAO.getAddressContactPersonDetailsMap ( customer.getDefaultShippingAddressId() ) );
                          request.setAttribute ( "salesPersonsRegionList" , NewCustomerDAO.loadAllSalesPersonsWithRegions() );
                          request.setAttribute ( "allShippingContactPersonsMap", CustomerDAO.getAllContactPersonsOfType( customer.getCustomerId(), "Shipping") );
                          request.setAttribute ( "allBillingContactPersonsMap", CustomerDAO.getAllContactPersonsOfType( customer.getCustomerId(), "Billing") );

                          ArrayList shipMethods = CustomerDAO.loadAllShippingMethods ( custId );
                          request.setAttribute ( "shippingMethods", shipMethods );
                          request.setAttribute ( "deliveryTerms", CustomerDAO.getAllDeliveryTerms(null) );
                          session.setAttribute ( "showCustomer", "FALSE" );
                          customer.setEndUserName ( "" );
                          request.setAttribute ( "endUsers", EndUserDAO.getAllEndUserNames ( custId ) );
                          request.setAttribute ( "allShippingTerms", SalesDAO.getAllShippingTerms());
                          flag = true;
                          return (mapping.findForward ("editCustomer"));
                    }
                    CustomerDAO.saveShipAlertEmails ( dbTransaction, subform.getCustomer() );
                    CustomerDAO.saveCustomerHolds ( dbTransaction, subform.getCustomer(), user.getUserName(), false );
                    CustomerDAO.saveCustomerHolds ( dbTransaction, subform.getCustomer(), user.getUserName(), true );
                    request.setAttribute ( "shippingMethods", CustomerDAO.loadAllShippingMethods ( dbTransaction, customerId ) );
                    request.setAttribute ( "deliveryTerms", CustomerDAO.getAllDeliveryTerms(null) );
                    }
                }
                if ( customer.getIsConsignee() )
                {
                    VendorDAO.createUpdateVendor( dbTransaction, customer.getCustomerNumber(), customer.getCustomerNumber(), customer.getCustomerNumber(), Constants.LOCATION_TYPE_FINISHED_GOODS );
                }
                if ( ! ( customerId < 0 ) )
                    success = true;

            }
            catch ( ScalarException se )
            {
                // Exception while updating user profile
                // log it
                se.printStackTrace ();
            }
            finally
            {
                if(flag == false)
                {
                    if ( success == true )
                    {
                        dbTransaction.commit ();
                        if ( isNewCustomer == true )
                        {
                            info.put ( "Customer", "Saved Successfully" );
                        }
                        else
                        {
                            info.put ( "Customer", "Updated Successfully" );
                        }
                        info.put ( "View/Print ", "Click here to <a href='javascript:openCustomer();' onmouseover=\"window.status='Click here to View/print Customer Profiler';return true\" onmouseout=\"window.status='';return true\" > view/print </a>Customer Details" );

                        // Remove the obsolete form bean
                        if ( mapping.getAttribute () != null )
                        {
                            if ( "request".equals ( mapping.getScope () ) )
                                request.removeAttribute ( mapping.getAttribute () );
                            else
                                session.removeAttribute ( mapping.getAttribute () );
                        }
                        session.removeAttribute ( "locations" );
                        session.removeAttribute ( "showCustomer" );
                        request.setAttribute ( "customerId", Integer.toString ( customerId ) );
                    }
                    else
                    {
                        dbTransaction.rollback ();
                        errors.put ( ERROR_INTERNAL_SERVER_ERROR, ERROR_IN_SAVING_CUSTOMER );
                        errors.put ( ERROR_MESSAGE_CONTACT_SYS_ADMN, null );
                        session.setAttribute ( SessionKeys.ERROR_REPORT_SUBJECT, " Error: Could Not Save Customer " );
                        session.setAttribute ( SessionKeys.ERROR_REPORT, null );
                    }
                }
                else
                {
                  dbTransaction.rollback ();
                }
            }
            if ( !info.isEmpty () )
                request.setAttribute ( SessionKeys.MESSAGES, info );
            return ( mapping.findForward ( "successCustomer" ) );
        }

        return ( mapping.findForward ( "success" ) );

    }

    private void addNewShippingMethod ( DBTransaction dbTransaction,  HttpServletRequest request, HttpSession session, HashMap errors, HashMap info, CustomerForm subform )
    {
        int customerId = subform.getCustomer ().getCustomerId ();

        String method1 = null;
        String account1 = null;
        String finallabel = null;
        String newShippingMethodLabel = null;
        String shippingMethodLabel = null;
        boolean checkmethodexist = true;

        String shippingMethod1 = subform.getCustomer ().getShippingMethod1 ();
        String shippingAccount1 = subform.getCustomer ().getShippingAccount1 ();
        String shipMethod1 = request.getParameter ( "shipMethod1" );
        if ( ( !"-2".equalsIgnoreCase ( shipMethod1 ) ) && ( shipMethod1 != null ) && ( shipMethod1.trim ().length () != 0 ) )
        {
            int index1 = shipMethod1.indexOf ( "   #   " );
            if ( index1 != -1 && index1 != 0 )
            {
                finallabel = shipMethod1.substring ( 0, index1 );
            }
        }

        method1 = subform.getCustomer ().getNewShippingMethod1 ();
        account1 = subform.getCustomer ().getNewShippingAccount1 ();

        if ( account1 != null )
        {
            account1 = account1.trim ();
        }
        if ( method1 != null )
        {
            method1 = method1.trim ();
        }

        if ( "-2".equalsIgnoreCase ( shipMethod1 ) == true )
        {
            try
            {
                checkmethodexist = CustomerDAO.doesShippingMethodExist ( dbTransaction, customerId, method1, account1 );

                if ( checkmethodexist == false )
                {
                    try
                    {
                        CustomerDAO.insertShippingMethod ( dbTransaction, customerId, method1, account1 );

                        try
                        {
                            newShippingMethodLabel = MessageResources.getMessageResources ( Labels.APPLICATION_RESOURCE_PROPERTIES ).getMessage ( "label.sales.salesOrder.NewShippingMethod" );
                            shippingMethodLabel = MessageResources.getMessageResources ( Labels.APPLICATION_RESOURCE_PROPERTIES ).getMessage ( "label.sales.salesOrder.ShippingMethod" );
                            if ( newShippingMethodLabel == null )
                            {
                                newShippingMethodLabel = Labels.DEFAULT_NEW_SHIPPING_METHOD_LABEL;
                            }
                            if ( shippingMethodLabel == null )
                            {
                                shippingMethodLabel = Labels.DEFAULT_SHIPPING_METHOD_LABEL;
                            }
                        }
                        catch ( NullPointerException e )
                        {
                             newShippingMethodLabel = Labels.DEFAULT_NEW_SHIPPING_METHOD_LABEL;
                             shippingMethodLabel    = Labels.DEFAULT_SHIPPING_METHOD_LABEL;
                        }
                        info.put ( shippingMethodLabel, newShippingMethodLabel+" has been stored in database successfully" );
                        subform.getCustomer ().setShippingMethod1 ( method1 );
                        subform.getCustomer ().setShippingAccount1 ( account1 );
                    }
                    catch ( Exception se )
                    {
                        se.printStackTrace ();
                    }
               }
                else
               {
                    try
                    {
                        shippingMethodLabel = MessageResources.getMessageResources ( Labels.APPLICATION_RESOURCE_PROPERTIES ).getMessage ( "label.sales.salesOrder.ShippingMethod" );
                        if ( shippingMethodLabel == null )
                        {
                            shippingMethodLabel = Labels.DEFAULT_SHIPPING_METHOD_LABEL;
                        }
                    }
                    catch ( NullPointerException e )
                    {
                        shippingMethodLabel    = Labels.DEFAULT_SHIPPING_METHOD_LABEL;
                    }
                    errors.put ( method1 +" "+shippingMethodLabel+" already Exists ,Please enter another Shipping Method.", null );
                }
            }//try

            catch ( Exception e )
            {
                e.printStackTrace ();
            }
        }//if

        else
        {
            subform.getCustomer ().setShippingMethod1 ( finallabel );
            subform.getCustomer ().setShippingAccount1 ( shippingAccount1 );
        }
    }//method


    public static void addNewShippingInstructions( DBTransaction dbTransaction, HttpServletRequest request, HashMap errors, HashMap info, Customer customer )
    {
        int shippingInstructionsId  = customer.getShippingInstructionsId();
        String shippingInstructions = customer.getShippingInstructions();
        ArrayList shippingInstructionsList = null;
        boolean checkInstructionsexist = false;
        if ( shippingInstructionsId == -2  && shippingInstructions != null && shippingInstructions.trim().length() > 0 )
        {
            try {
                shippingInstructionsList = NewSalesOrderDAO.loadShippingInstructions(null);
            } catch ( Exception e ) {
                e.printStackTrace();
            }
            for ( int i = 0; i < shippingInstructionsList.size(); i++ ) {
                LabelValueBean labelValueBean = (LabelValueBean) shippingInstructionsList.get(i);
                if ( ( shippingInstructions.trim()).equalsIgnoreCase( labelValueBean.getLabel().trim() ) ) {
                    checkInstructionsexist = true;
                    break;
                }
            }
            if ( !checkInstructionsexist )
            {
                try {
                    shippingInstructionsId = NewSalesOrderDAO.saveShippingInstructions( dbTransaction, shippingInstructions );
                    customer.setShippingInstructionsId( shippingInstructionsId );
                    shippingInstructionsList.add( new org.apache.struts.util.LabelValueBean( shippingInstructions, shippingInstructionsId+"" ) );
                    info.put ( "New Shipping Instructions added successfully", null );
                } catch( Exception e){
                    errors.put("Shipping Instructions ","Could not save Shipping Instructions" );
                }
            } else {
                    errors.put("Shipping Instructions already exists, Please enter another Shipping Instructions ", null );
            }
        }
    }

    private void addNewShippingTerms( DBTransaction dbTransaction, HttpServletRequest request, HttpSession session, HashMap errors, HashMap info, Customer customer )
    {
        String shippingTerms = null;
        String newShippingTerms = null;
        boolean checkmethodexist = true;

        shippingTerms = customer.getShippingTerms();

        if( "-2".equalsIgnoreCase( shippingTerms ) == true )
        {
            try
            {
                newShippingTerms = customer.getNewShippingTerms();

                if( newShippingTerms != null )
                {
                    newShippingTerms = newShippingTerms.trim();
                }
                else
                {
                    newShippingTerms = "";
                }
                if( newShippingTerms != null && newShippingTerms.trim().length() != 0 )
                {
                    checkmethodexist = SalesDAO.doesShippingTermsExist( null, newShippingTerms );

                    if( checkmethodexist == false )
                    {
                        try
                        {
                            SalesDAO.insertShippingTerms( null, newShippingTerms );
                            ArrayList shippingTermsList = ( ArrayList ) SalesDAO.getAllShippingTerms();
                            shippingTermsList.add( newShippingTerms );
                            request.setAttribute( "allShippingTerms", shippingTermsList );
                            info.put( "New Pay Terms are added successfully", null );
                            customer.setShippingTerms( newShippingTerms );

                        }
                        catch( ScalarException se )
                        {
                            String shippingMethodLabel = null;
                            try
                            {
                                shippingMethodLabel = MessageResources.getMessageResources( Labels.APPLICATION_RESOURCE_PROPERTIES ).getMessage( "label.sales.salesOrder.ShippingMethod" );
                                if( shippingMethodLabel == null )
                                {
                                    shippingMethodLabel = Labels.DEFAULT_SHIPPING_METHOD_LABEL;
                                }
                            }
                            catch( NullPointerException e )
                            {
                                shippingMethodLabel = Labels.DEFAULT_SHIPPING_METHOD_LABEL;
                            }
                            errors.put( ERROR_INTERNAL_SERVER_ERROR, "Could not Save " + shippingMethodLabel + " Value." + newShippingTerms );
                            se.printStackTrace();
                        }
                    }
                    else
                    {
                        errors.put( newShippingTerms + " " + ERROR_SHIPPING_TERMS_EXISTS, null );
                    }
                }
            }
            catch( Exception e )
            {
                e.printStackTrace();
            }
        }
    }

    private void updateAddressesAndContactPersonsMap(ArrayList addresses, Map contactPersonsMap) throws Exception {
        int addId = 0;
        Address address = null;
        int size = addresses == null ? 0 : addresses.size();
        for (int bb = 0; bb < size; bb++) {
            address = (Address) addresses.get(bb);
            if (address.getAddressId() == -1) {
                addId = address.getLocAddressId();
            } else {
                addId = address.getAddressId();
            }
            ArrayList contactPersons = CustomerDAO.loadContactPersons(addId);

            address.setContactPersons(contactPersons);
            Map contactPersonMap = CustomerDAO.getAddressContactPersonDetailsMap(addId);
            contactPersonsMap.put("" + addId, contactPersonMap);
        }
    }
}